﻿/****************************************************************
*   作者：qq918
*   创建时间：2018/2/2 15:36:12
*   描述说明：
*****************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEngine;
namespace Model
{
  /// <summary>
  /// cvs帮助类
  /// </summary>
  public static class CSVHelper
  {
    /// <summary>
    /// 开始行数
    /// </summary>
    public static int START_LINE = 3;

    /// <summary>
    /// 读取cvs
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="data"></param>
    /// <returns></returns>
    public static List<T> FromCSV<T>(string data)
    {
      List<T> list = new List<T>();

      string[] temps = data.Split('\n');

      // 属性
      string[] fileds = temps[1].Split(',');

      for (int i = START_LINE; i < temps.Length; i++)
      {
        string[] values = temps[i].Split(',');

        Dictionary<string, string> dictionary = new Dictionary<string, string>();

        for (int x = 0; x < fileds.Length; x++)
        {
          dictionary.Add(fileds[x].Trim(), values[x].Trim());
        }

        PropertyInfo[] propertyInfos = typeof(T).GetProperties();

        T t = Activator.CreateInstance<T>();

        for (int j = 0; j < propertyInfos.Length; j++)
        {
          PropertyInfo propertyInfo = propertyInfos[j];
          string value = dictionary[propertyInfo.Name];

          if (propertyInfo.PropertyType.IsEnum)
          {
            propertyInfo.SetValue(t, Enum.Parse(propertyInfo.PropertyType, value), null);
          }
          else
          {
            propertyInfo.SetValue(t, Convert.ChangeType(value, propertyInfo.PropertyType), null);
          }
        }

        list.Add(t);
      }
      return list;
    }
  }
}